import base64
import os

from django_redis import get_redis_connection
from rest_framework import serializers

from oauth.models import OAuthQQUser
from oauth.utils import OAuthQQ
from users.models import User


class QQAuthUserSerializer(serializers.ModelSerializer):
    sms_code = serializers.CharField(label='验证码', write_only=True)
    access_token = serializers.CharField(label='openid', write_only=True)
    token = serializers.CharField(label='JWT token', read_only=True)
    mobile = serializers.RegexField(regex=r'^1[3-9]\d{9}$', label='电话号', write_only=True)

    class Meta:
        model = User
        fields = ("id", "username", "password", "mobile", "sms_code", "access_token", "token")
        extra_kwargs = {
            'username': {
                'read_only': True
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }

        }

    def validate(self, attrs):
        '''
        检验 短信验证码,
        检验 access_token 的有效性
        '''
        # 检验 access_token 的有效性
        # 获取access_token
        access_token = attrs['access_token']

        # 解密取出openid
        openid = OAuthQQ.check_save_user_token(access_token)
        if not openid:
            raise serializers.ValidationError('无效的token')
        attrs['openid'] = openid

        # 检验短信验证码
        # 验证手机验证码
        # 1.连接radis
        redis_conn = get_redis_connection('verify_codes')

        # 2. 用data里的电话号码取到验证码
        mobile = attrs['mobile']
        sms_code = redis_conn.get('sme_%s' % mobile)

        # 3. 然后对比验证
        if sms_code is None:
            raise serializers.ValidationError('短信验证码无效')

        if attrs['sms_code'] != sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')

        # 利用手机号取到user
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            user = None
        else:
            # 校验密码
            password = attrs['password']
            if not user.check_password(password):
                raise serializers.ValidationError('密码错误')

        attrs['user'] = user

        return attrs

    def create(self, validated_data):
        '''
        保存数据
        1. 判断手机号是否注册过
        1.1 如果没有 先注册
        2. 生成一个 token 并返回
        '''

        # 1. 判断手机号是否注册过
        user = validated_data['user']
        # 1.1 如果没有 先注册
        if user is None:
            # 随机生成字符串
            username = base64.b64encode(os.urandom(9)).decode()
            mobile = validated_data['mobile']
            password = validated_data['password']
            User.objects.create_user(username=username, mobile=mobile, password=password)

        # 绑定数据
        openid = validated_data['openid']
        OAuthQQUser.objects.create(
            user=user,
            openid=openid
        )

        self.context['view'].user = user

        # 2. 生成一个 token 并返回

        # 服务器生成jwt 保存用户数据
        from rest_framework_jwt.settings import api_settings
        # 生成载荷
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        # 生成JWT token
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        print(payload)
        token = jwt_encode_handler(payload)

        user.token = token

        return user
